<template>
  <div>
    <el-tree
      ref="tree"
      :data="data"
      show-checkbox
      default-expand-all
      node-key="id"
      highlight-current
      :props="defaultProps"
      :check-strictly="true"
    />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="hCancel">取消</el-button>
    </div>
  </div>

</template>

<script>
import { getPermissions } from '@/api/permissions'
import { tranListToTreeData } from '@/utils/index'
import { getRoleById, updateRoleById } from '@/api/user'
export default {
  props: {
    curId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 当前角色的信息
      roleInfo: {}
    }
  },
  created() {
    // 拿到所有的权限点
    this.setPermissions()
    // 根据ID获取角色详情
    this.setRoleById()
  },
  methods: {
    async setPermissions() {
      try {
        const res = await getPermissions()
        // console.log('getPermissions', res)
        this.data = tranListToTreeData(res.data.data)
        // 保存数据
      } catch (err) {
        console.log('getPermissions', err)
      }
    },
    // 根据ID获取角色详情
    async setRoleById() {
      try {
        const res = await getRoleById(this.curId)
        console.log('getRoleById', res)
        this.roleInfo = res.data.data
        this.$refs.tree.setCheckedKeys(res.data.data.permIds)
        // 保存数据
      } catch (err) {
        console.log('getRoleById', err)
      }
    },
    // 确定按钮
    async hSubmit() {
      try {
        this.roleInfo.permIds = this.$refs.tree.getCheckedKeys()
        await updateRoleById(this.roleInfo)
        this.$message.success('更新角色详情成功')
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 取消按钮
    hCancel() {
      this.$emit('success')
    }
  }
}
</script>

<style>

</style>
